import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BigScreenService } from '@src/app/services/bigScreen/bigScreen.service';
import { Params } from '@angular/router';
import { MessageService } from '../../services/message.service';
import { NzMessageService } from 'ng-zorro-antd';

declare const BMap: any;
declare const echarts: any;
@Component({
  selector: 'app-bigscreen',
  templateUrl: './bigscreen.component.html',
  styleUrls: ['./bigscreen.component.scss']
})
export class BigscreenComponent implements OnInit {
  public weight: number;
  public height;
  arr: any = [];
  public status: any;
  LEDswitchStatus: any;
  constructor(
    private http: HttpClient,
    public bigScreenService: BigScreenService,
    private message: NzMessageService,
  ) { }

  public project = JSON.parse(window.localStorage.getItem('project'));
  public today: any = Date.now();
  public timer: any;
  public weather: any;
  public weatherTimer: any;
  public getPersonInfoTimer: any;
  public ProjectUserForCheckIn = [];
  public ProjectUserForCheckOut = [];
  public lastManInfo;
  public todayPeoples;
  public pm25EchartsOption: any; // 环境监控图表
  public temperatureOption: any;
  public topList: any = {}; // 环境数据
  public optionPie: any;



  ngOnInit() {
    this.getWeather();
    this.initEchartsPie();
    this.QueryProjectUserAttendancesPagedList(1);
    this.QueryProjectUserAttendancesPagedList(2);
    setTimeout(() => {
      this.QueryProjectUserStayInsideReport();
    }, 100);

    // this.changedata();
    this.getLedStatus();
    this.handleQueryProjectsEnvironmentInfo();
    this.initEcharts();

    // this.weight = window.screen.width;
    // this.height = window.screen.height;

    // *****************轮询***********************
    this.timer = setInterval(() => {
      this.today = Date.now();
    }, 1000);
    this.weatherTimer = setInterval(() => {
      this.getWeather();
      location.reload();
    }, 10800000);

    this.getPersonInfoTimer = setInterval(() => {

      this.QueryProjectUserAttendancesPagedList(1);
      this.QueryProjectUserAttendancesPagedList(2);
      this.QueryProjectUserStayInsideReport();
      // this.changedata();
      this.handleQueryProjectsEnvironmentInfo();
      this.initEcharts();
      this.getLedStatus();
      location.reload();
    }, 600000);

    // ************* 轮询结束 ***********************

  }


  // LED
  public async getLedStatus() {
    const params = {

    };
    const res = await this.bigScreenService.QueryWindowsServiceStatus(params);
    this.status = res.result.status;
    this.LEDswitchStatus = res.result.switch;
  }



  // 模拟数据
  // public changedata() {
  //   const echartsPie = echarts.init(document.getElementById('echartsPie'));
  //   const color = ['#6AB0B8', '#D48265', '#C23531', '#2F4554', '#00658B', '#001745'];
  //   const i = Math.floor(Math.random() * 7);
  //   if (this.arr.length === 7) {
  //     this.arr = [];
  //   }
  //   if (i === 0) {
  //     return;
  //   }
  //   this.arr.push({ name: '木工-' + i, value: i, itemStyle: { color: color[i] } });

  //   // this.todayPeoples.totalCount = this.arr.forEach((element, index, arr) => {
  //   //   console.log(arr[index]);
  //   //   if (arr[index] && arr[index + 1]) {
  //   //     return arr[index].value + arr[index + 1].value;
  //   //   }
  //   // });
  //   this.optionPie.series[0].data = this.arr.sort(function (a, b) { return a.value - b.value; });
  //   echartsPie.setOption(this.optionPie);
  // }











  // 获取天气
  private getWeather() {

    this.http.jsonp('https://www.tianqiapi.com/api/?version=v6&cityid=101270101&appid=24626783&appsecret=Daxo2D1A', 'callback')
      .subscribe((data) => {
        this.weather = data;
      }
      );
  }

  /**
  * 饼图表初始变量
  */
  public initEchartsPie() {
    this.optionPie = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      series: [
        {
          name: '当前在场人数',
          type: 'pie',
          radius: '75%',
          center: ['50%', '50%'],
          data: [],
          roseType: 'radius',
          label: {
            normal: {
              textStyle: {
                color: 'rgba(255, 255, 255, 0.9)'
              }
            }
          },
          labelLine: {
            normal: {
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.9)'
              },
              smooth: 0.2,
              length: 10,
              length2: 20
            }
          },
          itemStyle: {
            normal: {
              // color: '#00E4FF',
              shadowBlur: 200,
              shadowColor: 'rgba(0, 0, 0, 0.8)'
            }
          },

          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function (idx) {
            return Math.random() * 1000;
          }
        }
      ]
    };
  }




  // 获取今天的在场人数及图表信息
  public async QueryProjectUserStayInsideReport() {


    const echartsPie = echarts.init(document.getElementById('echartsPie'));
    const params = {
      // code: this.project['code']
    };
    const color = ['#6AB0B8', '#D48265', '#C23531', '#2F4554', '#00658B', '#001745'];
    const colorIndex = Math.floor(Math.random() * 6);
    const res = await this.bigScreenService.QueryProjectUserStayInsideReport(params);
    if (res.success && res.result) {
      this.todayPeoples = res.result;
      // console.log(this.todayPeoples);
      const tempArr = [];
      if (this.todayPeoples.majorCount) {
        this.todayPeoples.majorCount.forEach(element => {
          tempArr.push({
            ...element,
            itemStyle: { color: color[colorIndex] }
          });
        });
        this.optionPie.series[0].data = tempArr.sort(function (a, b) { return a.value - b.value; });
        echartsPie.setOption(this.optionPie);
      }
    } else {
      this.message.warning(res.error);

    }
  }


  // 获取进出场人员及最后一个详情信息 type 进出类型：0全部，1进场，2出场
  public async QueryProjectUserAttendancesPagedList(type: number) {
    const params = {
      // code: this.project['code'],
      type,
      maxResultCount: 10,
      skipCount: 0
    };
    const res = await this.bigScreenService.QueryProjectUserAttendancesPagedList(params);

    if (res.success && res.result.items) {
      if (type === 1) {
        this.ProjectUserForCheckIn = res.result.items;
      }
      if (type === 2) {
        this.ProjectUserForCheckOut = res.result.items;
      }
      this.lastManInfo = res.result.items[0]; // 最近一个进出场人员信息
    } else {
      this.message.warning(res.error);

    }
  }


  // 初始化曲线图
  public initEcharts() {

    const dataArray = [{
      // type: 3,
      range: '7',
      option: 'temperatureOption'
    },
      //  {
      //   // type: 1,
      //   range: '7',
      //   option: 'temperatureOption'
      // }
    ];
    dataArray.forEach((data) => {
      this.handleQueryProjectsEnvironmentReport(data);
    });
    // this.echarts();
  }


  // 获取环境监测图表接口数据
  async handleQueryProjectsEnvironmentReport(params) {
    const echartsTem = echarts.init(document.getElementById('echartsTem'));
    const data = {
      // code: this.project['code'],
      ...params
    };
    await this.bigScreenService.QueryEnvironmentReport(data).then((res) => {
      // console.log(res);
      const option = params.option;

      if (option === 'pm25EchartsOption') {
        // this.setPm25EchartsOption();
        // this.pm25EchartsOption['xAxis'].data = [];
        // this.pm25EchartsOption['series'][0].data = [];
        // this.pm25EchartsOption['series'][1].data = [];
      } else if (option === 'temperatureOption') {
        this.setTemperatureOption();
        // this.temperatureOption['xAxis'].data = [];
        // this.temperatureOption['series'][0].data = [];

        this.temperatureOption['xAxis'].data = [];
        this.temperatureOption['series'][0].data = [];
        this.temperatureOption['series'][1].data = [];
      }


      res.result.report.forEach(element => {
        this[option].xAxis.data.push(element.date);
        if (option === 'temperatureOption') {
          this[option].series[1].data.push(element['h01Avg']);
          this[option].series[0].data.push(element['t01Avg']);
        }


      });
      echartsTem.setOption(this[option]);
    });

  }




  // 环境监测数据
  async handleQueryProjectsEnvironmentInfo() {
    const params = {

      // code: this.project['code'],
      range: 7
    };
    const res = await this.bigScreenService.QueryEnvironmentReport(params);
    // console.log(res.result);
    if (res.success) {
      this.topList = res.result;
      // console.log(this.topList);
    } else {
      this.message.warning(res.eorro);
    }

  }



  // 设置PM2.5曲线
  setPm25EchartsOption() {
    this.pm25EchartsOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '5%',
        top: '10%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [],
        axisLine: {
          lineStyle: {
            color: '#999999', // 颜色
            width: 1 // 粗细
          }
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          lineStyle: { color: 'none' }    // x轴刻度的颜色
        },
        axisLine: {
          lineStyle: {
            color: '#999999', // 颜色
            width: 1 // 粗细
          }
        }
      },
      series: [{
        itemStyle: {
          color: '#00d5d9'
        },
        lineStyle: {
          normal: {
            color: '#00d5d9'   // 线条颜色
          }
        },
        smooth: true, // 是否平滑曲线显示
        data: [70, 80, 60, 70, 80, 40, 50, 70],
        type: 'line',
        areaStyle: { // 区域填充样式
          normal: {
            // 线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#00d5d9' },
              { offset: 1, color: 'transparent' }
            ], false)
            // shadowColor: '#ea825b', //阴影颜色
            // shadowBlur: 20 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
          }
        },
        markLine: {
          silent: true,
          symbol: 'circle',
          symbolSize: 5
          // label: {
          //   position: "middle",
          //   formatter: "{b}"
          // },
          // data: [{
          //   name: "预警线",
          //   yAxis: 40,
          //   lineStyle: {
          //     type: 'solid',
          //     width: 2,
          //     color: "#d60000"
          //   },
          //   label: {
          //     position: "end",
          //     formatter: "{b}\n {c}"
          //   }
          // }]
        }
      }]
    };
  }

  // 设置温度曲线
  setTemperatureOption() {
    this.temperatureOption = {

      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        left: 'center',
        itemGap: 30,
        data: [
          {
            name: '温度',
            textStyle: { fontWeight: 'bold', color: '#999999' }
          },
          {
            name: '湿度',
            textStyle: { fontWeight: 'bold', color: '#999999' }
          }
        ]
      },
      grid: {
        left: '3%',
        right: '5%',
        top: '10%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [],
        axisLine: {
          lineStyle: {
            color: '#999999', // 颜色
            width: 1 // 粗细
          }
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          lineStyle: { color: 'none' }    // x轴刻度的颜色
        },
        axisLine: {
          lineStyle: {
            color: '#999999', // 颜色
            width: 1 // 粗细
          }
        }
      },
      series: [
        {
          name: '温度',
          itemStyle: {
            color: '#d96969'
          },
          lineStyle: {
            normal: {
              color: '#d96969'   // 线条颜色
            }
          },
          smooth: true, // 是否平滑曲线显示
          data: [30, 35, 37, 35, 34, 35, 30, 25],
          type: 'line',
          areaStyle: { // 区域填充样式
            normal: {
              // 线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#d96969' },
                { offset: 1, color: 'transparent' }
              ], false)
              // shadowColor: 'rgba(65, 159, 229, 0.7)', //阴影颜色
              // shadowBlur: 20 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
            }
          },
          markLine: {
            silent: true,
            symbol: 'circle',
            symbolSize: 5
            // label: {
            //   position: "middle",
            //   formatter: "{b}"
            // },
          }
        },
        {
          name: '湿度',
          itemStyle: {
            color: '#00d5d9'
          },
          lineStyle: {
            normal: {
              color: '#00d5d9'   // 线条颜色
            }
          },
          smooth: true, // 是否平滑曲线显示
          data: [0, 60, 40, 50, 70, 30, 50, 30],
          type: 'line',
          areaStyle: { // 区域填充样式
            normal: {
              // 线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#00d5d9' },
                { offset: 1, color: 'transparent' }
              ], false)
              // shadowColor: 'rgba(65, 159, 229, 0.7)', //阴影颜色
              // shadowBlur: 20 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
            }
          },
          markLine: {
            silent: true,
            symbol: 'circle',
            symbolSize: 5
            // label: {
            //   position: "middle",
            //   formatter: "{b}"
            // },
          }
        }]
    };
  }






  // 自动滚动列表
  public rollStart() {
    const ulbox = document.getElementsByClassName('list')[0];
    // 正常滚动不断给scrollTop的值+1,当滚动高度大于列表内容高度时恢复为0
    if (ulbox.scrollTop !== 0) {
      ulbox.scrollTop--;
    }
  }
  CloseEvent() {
    const DispClose = true;

    if (DispClose) {
      return '提示：您尚有未保存的内容，离开本页将丢失编辑内容！';
    }
  }




  ngOnDestroy() {
    clearInterval(this.timer);
    clearInterval(this.weatherTimer);
    clearInterval(this.getPersonInfoTimer);
    console.log('定时器已释放');
    window.onbeforeunload = this.CloseEvent;

    // window.alert(this.rollStart);
  }
}
